package com.elink.sys.util;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * 对象格式化工具类
 * @author 无处不在的二叔
 * @version 2016-09-28
 */
public class BeanSerializer {  
    
	private static final int DEFAULT_LEVEL = 1;
    
    /** 
     * 传入任意一个 object对象生成一个指定规格的object对象
     *  
     * @param object 任意对象 
     * @return object 任意对象 
     */  
    @SuppressWarnings("unchecked")
	private static Object serialize(Object object, Integer[] level) {  
    	//类型判断
        if (object != null) {  
        	if (object instanceof String || object instanceof Integer || object instanceof Double || object instanceof Long) {  
        		return object.toString();  
            } else if (object instanceof List){
            	return listBeanToMap((List<Object>)object, level);
            }else{
            	return beanToMap(object, level);
            } 
        }else{
        	return  null;
        }
    }  

    /** 
     * 传入任意一个 Javabean对象生成一个指定规格的Map对象
     *  
     * @param bean bean对象 
     * @param level 层级
     * @return TreeMap<String,Object>
     */  
    private static TreeMap<String,Object> beanToMap(Object bean, Integer[] level) {  
    	if(++level[0]>level[1]){
    		level[0]--;
    		return null;
    	}
    	TreeMap<String, Object> map = new TreeMap<String, Object>();
        PropertyDescriptor[] props = null;  
        try {  
            props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        if (props != null) {  
            for (int i = 0; i < props.length; i++) {  
                try {  //if(!(props[i].getPropertyType()).isInterface()){
                	String name = props[i].getName();
                    if(!isBlank(name)){
                    	map.put(name, serialize(props[i].getReadMethod().invoke(bean), level));
                    }
                } catch (Exception e) {  
                }  
            }  
        }
        level[0]--;
        return map;  
    }  

	/**
	 * 通过传入一个列表对象,调用指定方法将列表中的数据生成一个JSON规格指定字符串 
	 * @param list 对象集合
	 * @param level 层级
	 * @return List<Object>
	 */
    public static List<Object> listBeanToMap(List<?> list, Integer[] level) {  
    	List<Object> beans = new ArrayList<Object>();
        if (list != null && list.size() > 0) {  
            for (Object obj : list) {  
            	beans.add(serialize(obj, level));  
            }  
        }
        return beans;  
    }

    /** 
     * 重载serialize方法，默认层级为1
     *  
     * @param object 任意对象 
     * @return object 任意对象 
     */  
    public static Object serialize(Object object) {  
        return serialize(object, new Integer[]{0, DEFAULT_LEVEL});
    } 
 
    /** 
     * 重载serialize方法，指定转换层级
     *  
     * @param object 任意对象 
     * @return object 任意对象 
     */  
    public static Object serialize(Object object, Integer limit) {
        return serialize(object, new Integer[]{0,limit});
    }

    /** 
     * 传入任意一个 object对象生成一个指定规格的字符串 
     *  
     * @param object 任意对象 
     * @return String 
     */  
	private static String serializeJson(Object object, Integer[] level) {  
    	if(++level[0]>level[1]+1){
    		level[0]--;
    		return null;
    	}
        StringBuilder json = new StringBuilder();  
        if (object == null) {  
            json.append("\"\"");  
        } else if (object instanceof String || object instanceof Integer || object instanceof Double || object instanceof Long) {  
            json.append("\"").append(object.toString()).append("\"");  
        } else {  
            json.append(beanToJson(object, level));
        }  
        level[0]--;
        return json.toString();  
    }  

    /** 
     * 传入任意一个 Javabean对象生成一个指定规格的字符串 
     *  
     * @param bean bean对象 
     * @return String "{}" 
     */  
    private static String beanToJson(Object bean, Integer[] level) {  
        StringBuilder json = new StringBuilder();  
        json.append("{");  
        PropertyDescriptor[] props = null;  
        try {  
            props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        int count = 0;
        if (props != null) {  
            for (int i = 0; i < props.length; i++) {  
                try {  
                    if(!(props[i].getPropertyType()).isInterface()){  
                        String name = serializeJson(props[i].getName(), level);  
                        if(!isBlank(name)){
                        	count=1;
                            String value = serializeJson(props[i].getReadMethod().invoke(bean), level);  
                            json.append(name).append(":").append(value).append(",");  
                        }
                    }  
                } catch (Exception e) {  
                }  
            }  
        	json.setCharAt(json.length() - count, '}');
        } else {  
            json.append("}");  
        }  
        return json.toString();  
    }  

    /** 
     * 通过传入一个列表对象,调用指定方法将列表中的数据生成一个JSON规格指定字符串 
     *  
     * @param list 列表对象 
     * @return String "[{},{}]" 
     */  
    public static String listToJson(List<?> list, Integer[] limit) {  
        StringBuilder json = new StringBuilder();  
        json.append("[");  
        if (list != null && list.size() > 0) {  
            for (Object obj : list) {  
                json.append(serializeJson(obj, limit));  
                json.append(",");  
            }  
            json.setCharAt(json.length() - 1, ']');  
        } else {  
            json.append("]");  
        }  
        return json.toString();  
    }
    
    /** 
     * 重载serializeJson方法，默认层级为1
     *  
     * @param object 任意对象 
     * @return String 
     */  
    public static String serializeJson(Object object) { 
        return serializeJson(object, new Integer[]{0,DEFAULT_LEVEL});
    } 
 
    /** 
     * 重载serializeJson方法，指定转换层级
     *  
     * @param object 任意对象 
     * @return String 
     */  
    public static String serializeJson(Object object, Integer limit) {
        return serializeJson(object, new Integer[]{0,limit});
    }
    
    /**
     * 判断字符串是否为空
     */
	private static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(cs.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
}  